import Taro from "@tarojs/taro";
import md5 from "./md5js";
import { STORAGE_DATA } from "./constant";
import { hextob64, KEYUTIL, KJUR, RSAKey } from "jsrsasign";
/**
 * @description 获取当前页url
 */
export const getCurrentPageUrl = () => {
  let pages = Taro.getCurrentPages();
  let currentPage = pages[pages.length - 1];
  let url = currentPage.route;
  return url;
};

export const pageToLogin = () => {
  let path = getCurrentPageUrl();
  Taro.clearStorageSync();
  if (!path.includes("login")) {
    Taro.reLaunch({
      url: "/pages/login/index"
    });
  }
};

/** 对象转url参数 */
export const stringify = params => {
  const obj = typeof params === "object" && params !== null ? params : {};
  const isEmpty = v => v === "" || v === null || v === undefined;
  return Object.keys(obj)
    .filter(k => !isEmpty(obj[k]))
    .map(key => `${key}=${encodeURIComponent(obj[key])}`)
    .join("&");
};

export const repeat = (str = "0", times) => new Array(times + 1).join(str);
// 时间前面 +0
export const pad = (num, maxLength = 2) =>
  repeat("0", maxLength - num.toString().length) + num;
/** 时间格式的转换 */
export const formatTime = time =>
  `${pad(time.getHours())}:${pad(time.getMinutes())}:${pad(
    time.getSeconds()
  )}.${pad(time.getMilliseconds(), 3)}`;

export var globalData = {}; // 全局公共变量

// 使用es6的padStart()方法来补0
export const getYMDHMS = timestamp => {
  let time = timestamp ? new Date(timestamp) : new Date();
  let year = time.getFullYear();
  const month = (time.getMonth() + 1).toString().padStart(2, "0");
  const date = time
    .getDate()
    .toString()
    .padStart(2, "0");
  const hours = time
    .getHours()
    .toString()
    .padStart(2, "0");
  const minute = time
    .getMinutes()
    .toString()
    .padStart(2, "0");
  const second = time
    .getSeconds()
    .toString()
    .padStart(2, "0");

  return (
    year +
    "年" +
    month +
    "月" +
    date +
    "日 " +
    hours +
    "时" +
    minute +
    "分" +
    second +
    "秒"
  );
};

export function getFileName(filePath) {
  if (!filePath) return null;
  let index = filePath.lastIndexOf("/");
  const name = filePath.substring(index + 1);
  return name;
}

// 使用es6的padStart()方法来补0
export const getYMDHMS2 = timestamp => {
  let time = timestamp ? new Date(timestamp) : new Date();
  let year = time.getFullYear();
  const month = (time.getMonth() + 1).toString().padStart(2, "0");
  const date = time
    .getDate()
    .toString()
    .padStart(2, "0");
  const hours = time
    .getHours()
    .toString()
    .padStart(2, "0");
  const minute = time
    .getMinutes()
    .toString()
    .padStart(2, "0");
  const second = time
    .getSeconds()
    .toString()
    .padStart(2, "0");

  return (
    year + "-" + month + "-" + date + " " + hours + ":" + minute + ":" + second
  );
};

export function dateStr() {
  let date = new Date();
  if (date.getHours() >= 0 && date.getHours() < 12) {
    return "上午好";
  } else if (date.getHours() >= 12 && date.getHours() < 18) {
    return "下午好";
  } else {
    return "晚上好";
  }
}

/**
 * 校验手机号是否正确
 * @param phone 手机号
 */

export const verifyPhone = phone => {
  const reg = /^1[0-9]{10}$/;
  const _phone = phone.toString().trim();
  let toastStr =
    _phone === ""
      ? "手机号不能为空~"
      : !reg.test(_phone) && "请输入正确手机号~";
  return {
    errMsg: toastStr,
    done: !toastStr,
    value: _phone
  };
};

export const verifyStr = (str, text) => {
  const _str = str.toString().trim();
  const toastStr = _str.length ? false : `请填写${text}～`;
  return {
    errMsg: toastStr,
    done: !toastStr,
    value: _str
  };
};

// 截取字符串

export const sliceStr = (str, sliceLen) => {
  if (!str) {
    return "";
  }
  let realLength = 0;
  const len = str.length;
  let charCode = -1;
  for (var i = 0; i < len; i++) {
    charCode = str.charCodeAt(i);
    if (charCode >= 0 && charCode <= 128) {
      realLength += 1;
    } else {
      realLength += 2;
    }
    if (realLength > sliceLen) {
      return `${str.slice(0, i)}...`;
    }
  }

  return str;
};

/**
 * JSON 克隆
 * @param {Object | Json} jsonObj json对象
 * @return {Object | Json} 新的json对象
 */
export function objClone(jsonObj) {
  var buf;
  if (jsonObj instanceof Array) {
    buf = [];
    var i = jsonObj.length;
    while (i--) {
      buf[i] = objClone(jsonObj[i]);
    }
    return buf;
  } else if (jsonObj instanceof Object) {
    buf = {};
    for (var k in jsonObj) {
      buf[k] = objClone(jsonObj[k]);
    }
    return buf;
  } else {
    return jsonObj;
  }
}

export function MD5withRSA(signMd5) {
  if (!Taro.getStorageSync(STORAGE_DATA.PRIVATEKEY)) return;
  const pem = `-----BEGIN PRIVATE KEY-----${Taro.getStorageSync(
    STORAGE_DATA.PRIVATEKEY
  )}-----END PRIVATE KEY-----`;

  let key = KEYUTIL.getKey(pem);
  // 创建 Signature 对象
  let signature = new KJUR.crypto.Signature({ alg: "MD5withRSA" });
  // 传入key实例, 初始化signature实例
  signature.init(key);
  // 传入待签明文
  signature.updateString(signMd5);
  const signInfo = signature.sign();
  const sign = hextob64(signInfo);
  console.log("signature:", signInfo, sign);
  // 签名, 得到16进制字符结果
  return sign;
}

// 支付md5加密获取sign
export function signjs(jsonobj) {
  var signstr = obj2str(jsonobj);
  if (Taro.getStorageSync(STORAGE_DATA.USERID)) {
    signstr = signstr + "&key=" + Taro.getStorageSync(STORAGE_DATA.USERID);
  }
  var sign = md5(signstr); //验证调用返回或微信主动通知签名时，传送的sign参数不参与签名，将生成的签名与该sign值作校验。
  console.log("signstrkey:", signstr, signstr.length, sign, sign.toUpperCase());
  return sign.toUpperCase();
}

export function sortObj(obj) {
  if (obj instanceof Array) {
    let newArr = [];
    newArr = obj.map((item, index) => {
      return sortObj(item);
    });
    return newArr;
  } else if (obj instanceof Object) {
    let keys = Object.keys(obj);
    if (!(keys && keys.length > 0)) return null;
    keys = keys.sort(); //参数名ASCII码从小到大排序（字典序）；
    let newObj = {};
    keys.forEach(function(key) {
      if (obj[key] !== "" && obj[key] !== undefined && obj[key] !== null) {
        //如果参数的值为空不参与签名；
        newObj[key] = sortObj(obj[key]); //参数名区分大小写；
      }
    });
    return newObj;
  } else {
    return obj;
  }
}

//object转string,用于签名计算
export function obj2str(args) {
  if (!args) return;
  let newArgs = sortObj(args);
  console.log("sortObj\n", args, "\n", newArgs);
  let string = "";
  for (let k in newArgs) {
    string +=
      "&" +
      k +
      "=" +
      (typeof newArgs[k] == "object" ? JSON.stringify(newArgs[k]) : newArgs[k]);
  }
  string = string.substr(1);
  return string;
}

//随机函数的产生：
export function createNonceSt() {
  return Math.random()
    .toString(36)
    .substr(2, 15); //随机小数，转换36进制，去掉0.，保留余下部分
}

//时间戳产生的函数, 当前时间以证书表达，精确到秒的字符串
export function createTimeStamp() {
  return parseInt(new Date().getTime() / 1000) + "";
}

export function sort_ASCII(obj) {
  var arr = new Array();
  var num = 0;
  for (var i in obj) {
    arr[num] = i;
    num++;
  }
  var sortArr = arr.sort();
  var sortObj = {};
  for (var i in sortArr) {
    sortObj[sortArr[i]] = obj[sortArr[i]];
  }
  return sortObj;
}

/** 检查更新 */
export function checkForUpdate() {
  if (Taro.canIUse("getUpdateManager")) {
    const updateManager = Taro.getUpdateManager();
    updateManager.onCheckForUpdate(res => {
      // 请求完新版本信息的回调
      if (res.hasUpdate) {
        updateManager.onUpdateReady(() => {
          Taro.showModal({
            title: "更新提示",
            content: "新版本已经准备好，是否重启应用？",
            showCancel: false,
            confirmColor: "#40A3FF",
            success: res => {
              if (res.confirm) {
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                updateManager.applyUpdate();
              }
            }
          });
        });

        updateManager.onUpdateFailed(() => {
          // 新版本下载失败
          Taro.showModal({
            title: "更新提示",
            content: "新版本已经上线，请删除当前小程序，重新扫码进入",
            confirmColor: "#40A3FF",
            showCancel: false
          });
        });
      }
    });
  }
}
